route.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { listYears } from "@/lib/storage";
  2. import { getSession } from "@/lib/auth/session";
  3. import { canAccessBranch } from "@/lib/auth/permissions";
  4. import {
  5. withErrorHandling,
  6. json,
  7. badRequest,
  8. unauthorized,
  9. forbidden,
  10. } from "@/lib/api/errors";
  11. import { mapStorageReadError } from "@/lib/api/storageErrors";
  12. /**
  13. * Next.js Route Handler caching configuration (RHL-006):
  14. *
  15. * We force this route to execute dynamically on every request.
  16. *
  17. * Reasons:
  18. * - NAS contents can change at any time (new scans).
  19. * - Auth/RBAC-protected responses must not be cached/shared across users.
  20. * - We rely on a small storage-layer TTL micro-cache instead of Next route caching.
  21. */
  22. export const dynamic = "force-dynamic";
  23. /**
  24. * GET /api/branches/[branch]/years
  25. *
  26. * Happy-path response must remain unchanged:
  27. * { "branch": "NL01", "years": ["2024", ...] }
  28. */
  29. export const GET = withErrorHandling(
  30. async function GET(request, ctx) {
  31. const session = await getSession();
  32. if (!session) {
  33. throw unauthorized("AUTH_UNAUTHENTICATED", "Unauthorized");
  34. }
  35. // Next.js App Router: params are resolved asynchronously.
  36. const { branch } = await ctx.params;
  37. // Validate required route params early (client error => 400).
  38. if (!branch) {
  39. throw badRequest(
  40. "VALIDATION_MISSING_PARAM",
  41. "Missing required route parameter(s)",
  42. { params: ["branch"] }
  43. );
  44. }
  45. // RBAC: branch users can only access their own branch.
  46. if (!canAccessBranch(session, branch)) {
  47. throw forbidden("AUTH_FORBIDDEN_BRANCH", "Forbidden");
  48. }
  49. try {
  50. const years = await listYears(branch);
  51. return json({ branch, years }, 200);
  52. } catch (err) {
  53. // Convert filesystem errors into:
  54. // - 404 if the requested path does not exist (but NAS root is reachable)
  55. // - 500 for system-level storage failures
  56. throw await mapStorageReadError(err, { details: { branch } });
  57. }
  58. },
  59. { logPrefix: "[api/branches/[branch]/years]" }
  60. );